import React, { useState, useEffect } from 'react';
import './ShopPage.css';

function ShopPage() {
  const [userPoints, setUserPoints] = useState(500);
  const [exchangeHistory, setExchangeHistory] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const getAuthHeaders = () => {
    const token = localStorage.getItem('token');
    return {
      'Authorization': token ? `Bearer ${token}` : '',
      'Content-Type': 'application/json'
    };
  };

  const fetchUserPoints = async () => {
    try {
      const response = await fetch(`/user/userPoints?userId=${localStorage.getItem('userId')}`, {
        headers: getAuthHeaders()
      });

      if (!response.ok) {
        throw new Error('获取积分失败');
      }

      const data = await response.json();
      if (data.code === 200 && data.result) {
        setUserPoints(data.data);
      } else {
        throw new Error(data.message || '获取积分失败');
      }
    } catch (err) {
      console.error('获取积分错误:', err);
      setError(err.message);
    }
  };

  const handleExchange = async (type, amount) => {
    if (userPoints < amount) {
      alert('积分不足！');
      return;
    }

    if (!window.confirm(`确定要使用 ${amount} 积分兑换${type === 'upload' ? '上传量' : '邀请数'}吗？`)) {
      return;
    }

    setIsLoading(true);
    try {
      const endpoint = type === 'upload' 
        ? '/user/exchange-upload' 
        : '/user/exchange-invite';
      
      const response = await fetch(`${endpoint}?userId=${localStorage.getItem('userId')}&pointsToExchange=${amount}`, {
        method: 'POST',
        headers: getAuthHeaders(),
      });

      if (!response.ok) {
        throw new Error('兑换失败');
      }

      const data = await response.json();
      if (data.code === 0 && data.result) {
        setUserPoints(prev => prev - amount);
        alert('兑换成功！');
        // 更新兑换历史
        setExchangeHistory(prev => [{
          type,
          amount,
          time: new Date().toLocaleString()
        }, ...prev]);
      } else {
        throw new Error(data.msg || '兑换失败');
      }
    } catch (err) {
      console.error('兑换错误:', err);
      alert(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchUserPoints();
  }, []);

  return (
    <div className="shop-page">
      <div className="shop-container">
        <div className="shop-grid">
          {/* 左侧用户信息 */}
          <div className="user-info-panel">
            <div className="points-card">
              <h2>我的积分</h2>
              <div className="points-amount">{userPoints}</div>
              <p className="points-tip">积分可用于兑换上传量和邀请数</p>
            </div>
            
            <div className="exchange-history">
              <h3>兑换记录</h3>
              {exchangeHistory.length > 0 ? (
                <div className="history-list">
                  {exchangeHistory.map((record, index) => (
                    <div key={index} className="history-item">
                      <span className="history-type">
                        {record.type === 'upload' ? '上传量' : '邀请数'}
                      </span>
                      <span className="history-amount">-{record.amount}积分</span>
                      <span className="history-time">{record.time}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="no-history">暂无兑换记录</p>
              )}
            </div>
          </div>

          {/* 右侧商品列表 */}
          <div className="shop-items">
            <h2>积分兑换</h2>
            <div className="items-grid">
              <div className="shop-item">
                <div className="item-icon">📤</div>
                <h3>上传量</h3>
                <p className="item-desc">兑换1GB上传量</p>
                <div className="item-price">200积分</div>
                <button 
                  className="exchange-button"
                  onClick={() => handleExchange('upload', 200)}
                  disabled={isLoading || userPoints < 200}
                >
                  立即兑换
                </button>
              </div>

              <div className="shop-item">
                <div className="item-icon">🎫</div>
                <h3>邀请数</h3>
                <p className="item-desc">兑换1个邀请名额</p>
                <div className="item-price">100积分</div>
                <button 
                  className="exchange-button"
                  onClick={() => handleExchange('invite', 100)}
                  disabled={isLoading || userPoints < 100}
                >
                  立即兑换
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default ShopPage;

